package com.example.demo.service.impl;

import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import com.example.demo.security.jwt.JwtTokenUtil;
import com.example.demo.service.AdminService;
import com.example.demo.service.CourseService;
import com.example.demo.utils.CSVUtils;
import com.example.demo.utils.EntityMapUtils;
import com.example.demo.utils.IdcardUtils;
import com.example.demo.utils.RegUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.html.Option;
import java.util.*;


@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private CourseService courseService;

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseMapperInt courseMapperInt;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EduSystemMapper eduSystemMapper;

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private CourseRelationMapper courseRelationMapper;

    @Autowired
    private CourseRelationMapperInt courseRelationMapperInt;

    @Autowired
    private ChangeCourseMapper changeCourseMapper;

    private int cnumCode =0;
    private int cnameCode =1;
    private int csnameCode=2;
    private int cmnameCode=3;
    private int chourCode=4;
    private int ccreditCode=5;
    private int ctimeCode=6;
    private int croomCode=7;
    private int capacityCode=8;
    private int cintroCode=9;
    private int tidCode=10;

    @Override
    public List<Major> majorFindAll(){
        return majorMapper.findAll();
    }

    @Override
    public List<HashMap> schoolFindAll(){
        List<School> schools = schoolMapper.findAll();
        List<HashMap> resList = new ArrayList<>();
        for (School value : schools) {
            HashMap hashMap = new HashMap<>();
            Integer majors_total = 0;
            School school = value;
            List<Major> majors = school.getMajors();
            if (majors != null) {
                majors_total = school.getMajors().size();
            }
            hashMap.put("major_total", majors_total);
            hashMap.put("school_data", school);
            resList.add(hashMap);
        }
        return resList;
    }

    @Override
    public HashMap userFindAll() {
        List<User> users = userMapper.findAll();
        List<HashMap> userinfos = new ArrayList<>();
        HashMap resMap = new HashMap<>();
        Integer userTotal = users.size();
        resMap.put("total",userTotal);
        for(int i=0;i<userTotal;i++){
            HashMap userInf = new HashMap<>();
            User user = users.get(i);
            userInf.put("id",user.getID());
            userInf.put("identityid",user.getIdentityId());
            userInf.put("name",user.getName());
            userInf.put("phonenumber",user.getPhoneNumber());
            userInf.put("mail",user.getMail());
            userInf.put("role",user.getRole());
            userInf.put("umajor",user.getUmajor());
            userInf.put("uschool",user.getUschool());
            userInf.put("ustatus",user.getUstatus());
            userinfos.add(userInf);
        }
        resMap.put("res",userinfos);
        return resMap;
    }


    @Override
    public boolean validateToken(String token){
        String ID = jwtTokenUtil.getUseridFromToken(token);

        return Objects.equals(ID,"1001");
    }

    //新增专业功能实现（学院）
    @Override
    public String addMajor(String sname, String mname){
        String Msg = null;
        if(majorMapper.findMajorByName(mname)!=null)
            Msg = "该专业已存在";
        if(Objects.equals(mname, "")&&Msg==null){
            if(schoolMapper.findSchoolByName(sname)!=null){
                Msg = "新增失败，学院已存在";
            }
            else{
                School school = new School();
                school.setSname(sname);
                schoolMapper.save(school);
                Msg = "新增成功，新增项为仅学院";
            }
        }
        if(Msg!=null)
            return Msg;

        //新增一个专业
        Major major=new Major();
        major.setMname(mname);
        major.setSname(sname);

        //学院已存在
        School school1 = schoolMapper.findSchoolByName(sname);
        if(school1!=null){
            major.setSchool(school1);
           // schoolMapper.save(school); //delete
            majorMapper.save(major);
            return "新增成功，新增项为仅专业";
        }
        //学院不存在
        else{
            School school=new School();
            school.setSname(sname);
            major.setSchool(school);
            schoolMapper.save(school);
            majorMapper.save(major);
            return"新增成功，新增项为专业和学院";
        }
    }

    //查询一个专业及其所属学院
    @Override
    public Major findMajorOne(String mname){
        return majorMapper.findMajorByName(mname);
    }

    //查询一个学院及其下属专业
    @Override
    public School findSchoolOne(String sname){
        return schoolMapper.findSchoolByName(sname);
    }

    //修改学院功能实现
    @Override
    public String changeSchool(String oldSname, String newSname){
        if(schoolMapper.findSchoolByName(oldSname)==null){
            return "修改失败，原学院不存在";
        }
        if(schoolMapper.findSchoolByName(newSname)!=null){
            return "修改失败，新学院名称与已有学院重合";
        }

        School school = schoolMapper.findSchoolByName(oldSname);

        List<Major> majors=school.getMajors();

        List<User> users = userMapper.findUserBySchool(oldSname);
        List<Course> courseList=new ArrayList<>();

        for (Major major : majors) {
            List<Course> courses=major.getCourses();
            courseList.addAll(courses);
            major.setSname(newSname);
            majorMapper.save(major);
        }

        for(Course course : courseList){
            course.setCsname(newSname);
            courseMapper.save(course);
        }

        for(User user : users){
            user.setUschool(newSname);
            userMapper.save(user);
        }

        school.setSname(newSname);
        schoolMapper.save(school);

        return "修改成功";
    }

    //修改专业名称，或将其修改至另一学院下属
    @Override
    public String changeMajor(String newSname, String oldMname, String newMname){
        Major major = majorMapper.findMajorByName(oldMname);
        Major major_lib=majorMapper.findMajorByName(newMname);
        if(major==null){
            return "修改失败，原专业不存在";
        }
        if (major_lib != null) {
            if(!Objects.equals(major_lib.getMid(), major.getMid())){
                return "修改失败，新专业名称与已有专业重合";
            }
        }

        //修改专业的课程
        List<Course> courses = major.getCourses();
        for(Course course:courses){
            course.setCsname(newSname);
            course.setCmname(newMname);
            courseMapper.save(course);
        }

        //修改专业的人员
        List<User> users = userMapper.findUserByMajor(oldMname);
        for(User user: users){
            user.setUschool(newSname);
            user.setUmajor(newMname);
            userMapper.save(user);
        }

        //修改专业所属学院
        School school_lib = schoolMapper.findSchoolByName(newSname);
        if(school_lib==null){
            School school = new School();
            school.setSname(newSname);
            major.setMname(newMname);
            major.setSname(newSname);
            major.setSchool(school);
            schoolMapper.save(school);
            majorMapper.save(major);
        }
        else{
            major.setMname(newMname);

            major.setSname(newSname);
            major.setSchool(school_lib);
            majorMapper.save(major);
        }
        return "修改成功";

    }

    @Override
    public String deleteSchool(String sname){
        if(schoolMapper.findSchoolByName(sname)==null){
            return "删除失败，该学院不存在";
        }
        School school = schoolMapper.findSchoolByName(sname);
        schoolMapper.delete(school);
        List<User> users = userMapper.findUserBySchool(sname);
        for(User user : users){
            user.setUschool("暂无学院");
            user.setUmajor("暂无专业");
            userMapper.save(user);
        }

        return "删除成功";
    }

    @Override
    public String deleteMajor(String mname){
        if(majorMapper.findMajorByName(mname)==null){
            return "删除失败，该专业不存在";
        }
        Major major=majorMapper.findMajorByName(mname);
        majorMapper.delete(major);
        List<User> users = userMapper.findUserByMajor(mname);
        for(User user:users){
            user.setUmajor("暂无专业");
            userMapper.save(user);
        }

        return "删除成功";
    }

    //重复校验，与数据库比对
    @Override
    public HashMap sameCheckLib(String newidentityid, String newmail, String newphonenumber, String id){
        HashMap resMap = new HashMap();
        boolean isCorrect = true;
        User userPID = adminMapper.findUserByPersonid(newidentityid);
        List<User> userEML = adminMapper.findUserByEmail(newmail);
        List<User> userMBL = adminMapper.findUserByMobile(newphonenumber);
        if(userPID!=null&& !Objects.equals(userPID.getID(), id)){
            isCorrect = false;
            resMap.put("identityid","exist");
            System.out.println(userPID.getID());

        }
        if(userEML.size()!=0 && !Objects.equals(newmail, "")){
            if(!Objects.equals(userEML.get(0).getID(), id)) {
                isCorrect = false;
                resMap.put("mail", "exist");
                System.out.println("mail");
            }
        }
        else{
            System.out.println("mail");

        }
        if(userMBL.size()!=0 && !Objects.equals(newphonenumber, "")){
            System.out.println(userMBL);

            if(!Objects.equals(userMBL.get(0).getID(), id)) {
                isCorrect = false;
                resMap.put("phonenumber", "exist");
                System.out.println("mbl");

            }
        }
        else{
            System.out.println("mail");

        }
        if(isCorrect)
            resMap.put("isCorrect",true);
        else
            resMap.put("isCorrect",false);
        return resMap;
    }

    //管理员修改用户个人信息
    @Override
    public HashMap changeUserInfo(String id, String newname, String newidentityid, String newmail,
                                  String newphonenumber, String newrole, String newuschool, String newumajor){
        User user = adminMapper.findUserById(id);
        HashMap resMap = new HashMap<>();
        boolean isCorrect = true;

        //格式校验
        resMap = RegUtils.formatCheck(id,newname,newidentityid,newphonenumber,newrole,newuschool,newumajor,newmail);
        if(resMap.get("result")=="false")
            isCorrect = false;
        resMap.remove("result");

        //重复校验
        resMap.putAll(sameCheckLib(newidentityid, newmail, newphonenumber, id));
        if(isCorrect)
            isCorrect=(boolean)resMap.get("isCorrect");
        resMap.remove("isCorrect");


        //学院专业校验
        if(schoolMapper.findSchoolByName(newuschool)==null){
            isCorrect = false;
            resMap.put("school","none");

        }
        if(majorMapper.findMajorByName(newumajor)==null){
            isCorrect = false;
            resMap.put("major","none");

        }

        //重复校验-与原信息比对
        resMap.putAll(RegUtils.sameCheck(user,newrole,newidentityid,newmail,newphonenumber,newname,newuschool,newumajor));

        System.out.println(resMap.size());
        if(!isCorrect)
            resMap.put("result","fail");
        else {
            resMap.put("result", "success");
            user.setUmajor(newumajor);
            user.setUschool(newuschool);
            user.setPhoneNumber(newphonenumber);
            user.setRole(newrole);
            user.setIdentityId(newidentityid);
            user.setMail(newmail);
            user.setName(newname);
            adminMapper.save(user);
        }


        return resMap;

    }

    //管理员审核新增课程
    @Override
    public String reviewAdd(String review,int cid) {

        //Course course=courseMapper.findCourseByTimeRoom(ctime,croom);
        Course course = courseMapperInt.getById(cid);

        //若未能查找到课程
        if(course==null){
            course.setCstatus("normal");
            return "课程信息有误";
        }


        User teacher1 = course.getTeacher();

        HashMap hashMap = courseService.validateCourse(course,teacher1);

        if(hashMap.get("result")!="success"){
            courseMapper.delete(course);
            course.setCstatus("normal");
            return "新增课程与已有课程冲突";
        }

        if(review.equals("disagree")){
            courseMapper.delete(course);
            course.setCstatus("normal");
            return "不通过新增已处理";
        }

        if(review.equals("agree")){
            String ctime = course.getCtime();
            String [] periods=ctime.split(",");

            for (int i = 0; i < periods.length; i++) {

                CourseRelation courseRelation = new CourseRelation();
                courseRelation.setCid(cid);
                courseRelation.setRname(course.getCroom());
                User teacher = course.getTeacher();
                if(teacher!=null){
                    courseRelation.setTid(teacher.getID());
                }

                int period=Integer.parseInt(periods[i]);
                courseRelation.setPeriod(period);

                courseRelationMapper.save(courseRelation);
            }

            School school=course.getSchool();
            if(school!=null){
                course.setSchool(school);
            }

            Major major=course.getMajor();
            if(major!=null){
                course.setMajor(major);
            }

            course.setCstatus("normal");
            courseMapper.save(course);
            return "通过新增已处理";
        }

        return "错误信息";
    }

    //获取课程信息
    @Override
    public HashMap courseList(){
        HashMap resMap = new HashMap();
        List<Course> courseList = courseMapper.findByStatus("normal");
        courseList.addAll(courseMapper.findByStatus("toChange"));
        courseList.addAll(courseMapper.findByStatus("toDelete"));
        List<Map> resList = new ArrayList<>();
        for(Course course:courseList){
            Map<String,Object> map= EntityMapUtils.entityToMap(course);
            map.remove("teacher");
            map.remove("major");
            map.remove("school");
            map.put("tid",course.getTeacher().getID());
            resList.add(map);
        }
        resMap.put("total",resList.size());
        resMap.put("res",resList);
        return resMap;
    }

    //管理员新增课程
    @Override
    public HashMap<String,String> addCourse(Course course,User teacher){
        HashMap<String,String> hashMap=courseService.validateCourse(course,teacher);

        if(Objects.equals(hashMap.get("result"), "success")){
            //存储课程信息
            School school = schoolMapper.findSchoolByName(course.getCsname());
            Major major = majorMapper.findMajorByName(course.getCmname());
            if(school==null||major==null){
                hashMap.put("11","学院或专业信息有误");
                return hashMap;
            }
            course.setSchool(school);
            course.setMajor(major);
            course.setTeacher(teacher);
            course.setCstatus("normal");
            courseMapper.save(course);

            //存储课程时间教室信息
            String ctime = course.getCtime();
            String [] periods=ctime.split(",");
            for (int i = 0; i < periods.length; i++) {

                CourseRelation courseRelation = new CourseRelation();
                courseRelation.setCid(course.getCid());
                courseRelation.setRname(course.getCroom());
                if(teacher!=null){
                    courseRelation.setTid(teacher.getID());
                }
                int period=Integer.parseInt(periods[i]);
                courseRelation.setPeriod(period);
                courseRelationMapper.save(courseRelation);
            }
        }
        return hashMap;
    }

    //管理员修改课程
    @Override
    public HashMap<String, String> changeCourse(Course cCourse, User teacher) {
        HashMap<String,String> hashMap=new HashMap<>();
        int cid = cCourse.getCid();
        if(!courseMapperInt.existsById(cid)){
            hashMap.put("courseId","课程信息错误");
            return hashMap;
        }
        Course course=courseMapperInt.getById(cid);

        System.out.println(cCourse.getSchool());
        hashMap=courseService.validateCourse(cCourse,teacher);
        boolean isValid = courseService.validateCourseNoCheckSame(hashMap,cCourse,course);


        if(isValid) {
            hashMap.put("room","ok");
            hashMap.put("teacher","ok");
            hashMap.put("result","success");

            courseService.copyCourse(cCourse,course,teacher);

            String[] split = course.getCtime().split(",");
            List<CourseRelation> courseRelations = new ArrayList<>();
            List<CourseRelation> courseRelationList = courseRelationMapperInt.findByCid(course.getCid());
            courseRelationMapper.deleteAll(courseRelationList);

            for (String s : split) {
                CourseRelation courseRelation = new CourseRelation();
                Integer period = Integer.parseInt(s);
                courseRelation.setCid(course.getCid());
                courseRelation.setPeriod(period);
                courseRelation.setRname(course.getCroom());
                courseRelation.setTid(teacher.getID());
                courseRelations.add(courseRelation);
            }
            courseRelationMapper.saveAll(courseRelations);

        }

        return hashMap;
    }

    @Override
    public Integer deleteCourse(Integer cid) {
        Integer successCode = 200;
        Integer errCode = 500;

        if(!courseMapperInt.existsById(cid))
            return errCode;
        Course course = courseMapperInt.getById(cid);

        if(Objects.equals(course.getCstatus(), "normal")) {
            courseMapper.delete(course);
            courseMapper.delete(course);
            List<CourseRelation> courseRelations = courseRelationMapperInt.findByCid(cid);
            int csize =courseRelations.size();
            for (int i = 0; i < csize; i++) {
                courseRelationMapper.delete(courseRelations.get(i));
            }
            return successCode;
        }
        else{
            return errCode;
        }
    }

    @Override
    public Integer addRoom(String rname, Integer capacity) {
        Integer successCode = 200;
        Integer errCode = 500;
        if(roomMapper.existsById(rname)){
            return errCode;
        }
        Room room =new Room(rname,capacity);
        roomMapper.save(room);
        return successCode;
    }

    //管理员修改教室
    @Override
    public Integer changeRoom(String oldrname, String newrname, int capacity) {
        Integer successCode = 200;
        Integer errCode = 500;
        if(!roomMapper.existsById(oldrname))
            return errCode;
        if(roomMapper.existsById(newrname)&&!newrname.equals(oldrname))
            return errCode;
        Room oldroom=roomMapper.getById(oldrname);
        roomMapper.delete(oldroom);
        Room newroom =new Room(newrname,capacity);
        roomMapper.save(newroom);

        List<Course> courses=courseMapper.findByCroom(oldrname);
        List<Course> newCourses = new ArrayList<>();
        for (int i = 0; i < courses.size(); i++) {
            courses.get(i).setCroom(newrname);
            newCourses.add(courses.get(i));

        }
        courseMapper.saveAll(newCourses);
        List<CourseRelation> courseRelations=courseRelationMapper.findByRoom(oldrname);

        for (int i = 0; i < courseRelations.size(); i++) {
            courseRelations.get(i).setRname(newrname);
        }
        return successCode;
    }

    //管理员删除教室
    @Override
    public Integer deleteRoom(String rname) {
        Integer successCode = 200;
        Integer errCode = 500;
        List<Course> courses=courseMapper.findByCroom(rname);
        if(courses.size()>0)
            return errCode;
        if(!roomMapper.existsById(rname))
            return errCode;
        Room room=roomMapper.getById(rname);
        roomMapper.delete(room);
        return successCode;
    }


    //审核删除课程
    @Override
    public String reviewDelete(String review,int cid) {
        Course course = courseMapperInt.getById(cid);

        //若未能查找到课程
        if(course==null)
            return "课程信息有误";

        if(review.equals("disagree")){
            course.setCstatus("normal");
            courseMapper.save(course);
            return "不通过删除已处理";
        }

        if(review.equals("agree")){
            courseMapper.delete(course);
            List<CourseRelation> courseRelations = courseRelationMapperInt.findByCid(cid);
            int csize =courseRelations.size();
            for (int i = 0; i < csize; i++) {
                courseRelationMapper.delete(courseRelations.get(i));
            }
            return "通过删除已处理";
        }

        return "错误信息";
    }

    //管理员审核修改
    @Override
    public String reviewChange(String review, int cid) {
        Course course = courseMapperInt.getById(cid);
        ChangeCourse changeCourse =changeCourseMapper.getById(cid);

        //若未能查找到课程
        if(course==null)
            return "课程信息有误";

        if(review.equals("disagree")){
            changeCourseMapper.delete(changeCourse);
            course.setCstatus("normal");
            courseMapper.save(course);
            return "不通过修改已处理";
        }

        if(review.equals("agree")){

            //若数据库中有其他课程已为这一时间和教室
            boolean isPresent = false;
            String[] time = changeCourse.getCtime().split(",");
            List<Integer> periodsInt = new ArrayList<>();
            for(String s : time){
                int timeInt = Integer.parseInt(s);
                periodsInt.add(timeInt);
            }
            if(courseRelationMapper.findByRoomAndPeriods(periodsInt,changeCourse.getCroom())>0){
                isPresent=true;
            }

            if(isPresent){
                course.setCstatus("normal");
                courseMapper.save(course);
                changeCourseMapper.delete(changeCourse);
                return "无法通过修改";
            }

            //修改原课程的信息
            course.setCname(changeCourse.getCname());
            course.setCroom(changeCourse.getCroom());
            course.setCtime(changeCourse.getCtime());
            course.setCstatus("normal");

            //删除原课程的时间、教室信息
            List<CourseRelation> courseRelations = courseRelationMapperInt.findByCid(cid);
            courseRelationMapper.deleteAll(courseRelations);


            //新增新课程的时间、教室信息
            String ctime = changeCourse.getCtime();
            String [] periods=ctime.split(",");

            for (int i = 0; i < periods.length; i++) {

                CourseRelation courseRelation = new CourseRelation();

                courseRelation.setCid(cid);
                courseRelation.setRname(course.getCroom());
                User teacher = course.getTeacher();
                if(teacher!=null){
                    courseRelation.setTid(teacher.getID());
                }

                int period=Integer.parseInt(periods[i]);
                courseRelation.setPeriod(period);

                courseRelationMapper.save(courseRelation);
            }
            courseMapper.save(course);
            changeCourseMapper.delete(changeCourse);
            return "通过修改已处理";
        }

        return "错误信息";
    }

    @Override
    public String validateschoolmajor(HashMap<String,String>properties, List<String> snameList, List<String> mnameList){
        String uschool = properties.get("uschool");
        String umajor = properties.get("umajor");
        String error = "";
        if(!Objects.equals(uschool, "")){
            System.out.println(uschool);
            if(!snameList.contains(uschool)) {
                //isCorrect = false;
                error += "学院不存在; ";
            }
        }
        if(!Objects.equals(umajor, "") ){
            if(!mnameList.contains(umajor)) {
                //isCorrect = false;
                error += "专业不存在; ";
            }
        }
        return error;
    }

    @Override
    public User setUser(HashMap<String,String> properties){
        User user = new User();
        user.setUmajor(properties.get("umajor"));
        user.setUschool(properties.get("uschool"));
        user.setMail(properties.get("mail"));
        user.setName(properties.get("name"));
        user.setID(properties.get("id"));
        user.setIdentityId(properties.get("identityid"));
        user.setRole(properties.get("role"));
        user.setPhoneNumber(properties.get("phonenumber"));
        user.setPassword("ABCD1234");
        if(Objects.equals(properties.get("role"), "student"))
            user.setUstatus("在读");
        if(Objects.equals(properties.get("role"), "teacher"))
            user.setUstatus("在岗");
        return user;
    }

    @Override
    public String sameCheckStr(HashMap<String,String> properties){
        String error="";
        if (adminMapper.existsById(properties.get("id"))) {
            //isCorrect = false;
            error += "id已存在; ";
        }
        List<User> users1 = adminMapper.findUserByEmail(properties.get("mail"));
        if (!Objects.equals(properties.get("mail"), "") && users1.size()!=0) {
            //isCorrect = false;
            String id_lib = users1.get(0).getID();
            error += "邮箱与id: " + id_lib + " 用户相同; ";
        }
        List<User> users2 = adminMapper.findUserByMobile(properties.get("phonenumber"));
        if (!Objects.equals(properties.get("phonenumber"), "") && users2.size()!=0) {
            //isCorrect = false;
            String id_lib = users2.get(0).getID();
            error += "手机号与id: " + id_lib + " 用户相同; ";
        }
        User user3 = adminMapper.findUserByPersonid(properties.get("identityid"));
        if (user3 != null) {
            //isCorrect = false;
            String id_lib = user3.getID();
            error += "身份证号与id: " + id_lib + " 用户相同; ";
        }
        return error;
    }




    //上传CSV文件录入用户
    @Override
    public List<String> addUsers(List<List<String>> userList){
        User user = new User();
        List<String> errorlist=new ArrayList<>();
        List<String> snameList = schoolMapper.selectNameAll();
        List<String> mnameList = majorMapper.selectNameAll();
        List<User> usersRes = new ArrayList<>();
        for(int i=0;i<userList.size();i++){
            List<String> value=userList.get(i);
            boolean isCorrect=true;

            HashMap<String,String> properties = CSVUtils.getColsFromValue(value);

            String error = "";
            int row=i+1;
            error+="error: row " + row + ": ";

            String sameCheckLibStr = sameCheckStr(properties);
            if(sameCheckLibStr.length()!=0){
                isCorrect=false;
                error+=sameCheckLibStr;
            }

            String formatStr = RegUtils.formatCheckString(properties);
            if(formatStr.length()!=0){
                isCorrect=false;
                error+=formatStr;
            }

            String validateSchoolMajorStr = validateschoolmajor(properties,snameList,mnameList);
            if(validateSchoolMajorStr.length()!=0){
                isCorrect=false;
                error+=validateSchoolMajorStr;
            }

            if(isCorrect){
                user=setUser(properties);
                usersRes.add(user);
            }
            else {
                errorlist.add(error);
            }
        }
        adminMapper.saveAll(usersRes);
        return errorlist;
    }

    @Override
    public StringBuilder existError(List<String> value){
        StringBuilder existError = new StringBuilder();
        int tidCode=10;

        String tid = value.get(tidCode);
        User teacher = userMapper.findUserByID(tid);
        if(teacher==null){
            existError.append("教师不存在; ");
            return existError;
        }

        if(!Objects.equals(teacher.getRole(), "teacher")){
            existError.append("该用户没有开课权限; ");
            return existError;
        }
        return null;
    }

    @Override
    public List<CourseRelation> setRelation(Course course,String ctime, User teacher){
        String[] split = ctime.split(",");
        List<CourseRelation> relations = new ArrayList<>();

        for (String s : split) {
            CourseRelation courseRelation = new CourseRelation();
            Integer period = Integer.parseInt(s);
            courseRelation.setPeriod(period);
            courseRelation.setRname(course.getCroom());
            courseRelation.setTid(teacher.getID());
            relations.add(courseRelation);
        }
        return relations;
    }

    @Override
    public Course setCourse(List<String> value,User teacher){
        int cnumCode =0;
        int cnameCode =1;
        int csnameCode=2;
        int cmnameCode=3;
        int chourCode=4;
        int ccreditCode=5;
        int ctimeCode=6;
        int croomCode=7;
        int capacityCode=8;
        int cintroCode=9;
        int tidCode=10;
        Course course = new Course();
        course.setCnum(value.get(cnumCode));
        course.setCname(value.get(cnameCode));
        course.setCsname(value.get(csnameCode));
        course.setCmname(value.get(cmnameCode));
        course.setChour(Integer.parseInt(value.get(chourCode)));
        course.setCcredit(Integer.parseInt(value.get(ccreditCode)));

        //处理时间
        String getTime = value.get(ctimeCode);
        String ctime = getTime.replace("_",",");

        course.setCtime(ctime);
        course.setCroom(value.get(croomCode));
        course.setCapacity(Integer.parseInt(value.get(capacityCode)));
        course.setCintro(value.get(cintroCode));
        course.setCteacher(teacher.getName());
        return course;
    }

    @Override
    public HashSet<String> resultWithoutRepeat(Course course, User teacher,HashMap<String,String> hashMap){
        //HashMap<String,String> hashMap=courseService.validateCourse(course,teacher);
        //添加错误信息，不重复
        HashSet<String> hashSet = new HashSet<>();

        for (HashMap.Entry<String, String> entry : hashMap.entrySet()) {
            if(!Objects.equals(entry.getValue(), "ok")&&!Objects.equals(entry.getValue(), "提交失败"))
                hashSet.add(entry.getValue());
        }
        return hashSet;
    }

    @Override
    public StringBuilder errorListReturn(Course course,User teacher,HashMap<String,String> hashMap,HashSet<String> hashSet,List<School>schools,List<Major>majors,
                                        int schoolIndex, int majorIndex, List<CourseRelation> relations){
        StringBuilder error= new StringBuilder();
        if(Objects.equals(hashMap.get("result"), "success")){
            course.setSchool(schools.get(schoolIndex));
            course.setMajor(majors.get(majorIndex));
            course.setTeacher(teacher);
            course.setCstatus("normal");
            courseMapper.save(course);
            for (CourseRelation relation : relations) {
                relation.setCid(course.getCid());
            }
            courseRelationMapper.saveAll(relations);
            return null;
        }
        else{

            for (String s : hashSet) {
                error.append(s);
                error.append("; ");
            }
            return error;
        }
    }


    //上传CSV文件批量导入课程

    @Override
    public List<String> addCourses(List<List<String>> courseList){

        List<String> errorlist=new ArrayList<>();
        List<School> schools = schoolMapper.findAll();
        List<Major> majors = majorMapper.findAll();
        List<String> snameList = new ArrayList<>();
        List<String> mnameList = new ArrayList<>();

        for (School item : schools) {
            snameList.add(item.getSname());
        }
        for (Major item : majors) {
            mnameList.add(item.getMname());
        }

        for(int i=0;i<courseList.size();i++){
            Course course = new Course();

            StringBuilder error = new StringBuilder();
            int row=i+1;
            error.append("error: row ").append(row).append(": ");
            List<String> value=courseList.get(i);

            //格式校验
            StringBuilder numericError=RegUtils.Numeric(value);
            if(numericError!=null){
                errorlist.add(numericError.toString());
                continue;
            }

            StringBuilder existError = existError(value);
            if(existError!=null){
                errorlist.add(existError.toString());
                continue;
            }

            String tid = value.get(tidCode);
            User teacher = userMapper.findUserByID(tid);
            course = setCourse(value,teacher);

            int schoolIndex = snameList.indexOf(value.get(csnameCode));
            int majorIndex = mnameList.indexOf(value.get(cmnameCode));
            String getTime = value.get(ctimeCode);
            String ctime = getTime.replace("_",",");

            List<CourseRelation> relations = setRelation(course,ctime,teacher);
            HashMap<String,String> hashMap=courseService.validateCourse(course,teacher);
            //添加错误信息，不重复
            HashSet<String> hashSet=resultWithoutRepeat(course,teacher,hashMap);

            StringBuilder errors=errorListReturn(course,teacher,hashMap,hashSet,schools,majors,
                    schoolIndex, majorIndex, relations);
            error.append(errors);
            errorlist.add(errors.toString());

        }
        return errorlist;
    }

    //修改用户状态
    @Override
    public HashMap changeStatus(String uid, String ustatus){
        User user = adminMapper.findUserById(uid);
        boolean userExist = true;
        HashMap hashMap = new HashMap();
        if(user==null){
            userExist=false;
            hashMap.put("error","用户不存在");
        }
        if(userExist) {
            if (Objects.equals(user.getRole(), "admin")) {
                hashMap.put("error", "不能修改管理员状态");
            }
            if (Objects.equals(ustatus, "")) {
                hashMap.put("error", "状态不能为空");
            }
            if (Objects.equals(ustatus, user.getUstatus())) {
                hashMap.put("warning", "状态没有改变");
            }
        }

        if(userExist) {
            user.setUstatus(ustatus);
            adminMapper.save(user);
            if (Objects.equals(ustatus, "离职")) {
                List<Course> courses = courseMapper.findByTid(uid);
                courseMapper.deleteAll(courses);
                List<CourseRelation> courseRelations = courseRelationMapper.findByTid(uid);
                courseRelationMapper.deleteAll(courseRelations);

            }
            hashMap.put("success", "修改状态为" + ustatus);
        }
        return hashMap;
    }

    //管理员开启关闭选课功能
    @Override
    public String xkOpenClose(String select){
        if(eduSystemMapper.findById("xk").isPresent()){
            EduSystem eduSystem = eduSystemMapper.getById("xk");
            eduSystem.setSysstatus(Objects.equals(select, "true"));
            eduSystemMapper.save(eduSystem);
            if(Objects.equals(select,"true"))
                return "开启成功";
            else
                return "关闭成功";
        }
        else{
            return "更改失败";
        }
    }

    //获得选课状态
    @Override
    public String xkStatus(){
        if(eduSystemMapper.findById("xk").isPresent()){
            if(eduSystemMapper.findById("xk").get().isSysstatus())
                return "开启中";
            else
                return "关闭中";
        }
        else{
            return "查询失败";
        }
    }

    //管理课程时间
    @Override
    public Integer arrangeSchedule(List<Schedule> schedules){
        Integer errCode = 500;
        Integer correctCode = 200;
        int lateTime =0;
        for (Schedule schedule : schedules) {
            String starttime = schedule.getStarttime();
            int starttime_int = Integer.parseInt(starttime.replaceAll("[[\\s-:punct:]]", ""));
            String endtime = schedule.getEndtime();
            int endtime_int = Integer.parseInt(endtime.replaceAll("[[\\s-:punct:]]", ""));
            //结束时间不能早于开始时间
            if(starttime_int >= endtime_int){
                return errCode;
            }
            Integer schnum = schedule.getSchnum();
            //开始时间不能早于这节课之前的课程的结束时间
            if(starttime_int<lateTime){
                return errCode;
            }
            lateTime=endtime_int;
        }
        scheduleMapper.saveAll(schedules);
        return  correctCode;
    }

    //获取课程时间
    @Override
    public List getSchedule(){
        List<String> errorlist = new ArrayList<>();
        List<Schedule> schedules = scheduleMapper.findAll();
        if(schedules.size()>0)
            return schedules;
        else{
            errorlist.add("查询失败");
            return errorlist;
        }
    }

    //获取所有楼栋
    @Override
    public HashMap getBuildings(){
        List<String> errorlist = new ArrayList<>();
        List<Building> buildings = buildingMapper.findAll();
        if(buildings.size()>0){
            HashMap resMap = new HashMap();
            resMap.put("res",buildings);
            resMap.put("total",buildings.size());
            return resMap;
        }
        else{
            errorlist.add("查询失败");
            HashMap resMap = new HashMap();
            resMap.put("error",errorlist);
            return resMap;
        }
    }

    //获取所有教室
    @Override
    public HashMap getRooms(){
        List<String> errorlist = new ArrayList<>();
        List<Room> rooms = roomMapper.findAllByOrder();
        if(rooms.size()>0){
            HashMap resMap = new HashMap();
            resMap.put("res",rooms);
            resMap.put("total",rooms.size());
            return resMap;
        }
        else{
            errorlist.add("查询失败");
            HashMap resMap = new HashMap();
            resMap.put("error",errorlist);
            return resMap;
        }
    }

    @Override
    public HashMap reviewCourseList(){
        List<Course> coursesList = new ArrayList<>();
        HashMap resMap = new HashMap();


        //查看待删除课程
        HashMap deleteCourse = new HashMap<>();
        List<Course> deleteCourseList = courseMapper.findByStatus("toDelete");
        deleteCourse.put("res",deleteCourseList);
        deleteCourse.put("total",deleteCourseList.size());

        //查看待新增课程
        HashMap addCourse = new HashMap<>();
        List<Course> addCourseList = courseMapper.findByStatus("toAdd");
        addCourse.put("res",addCourseList);
        addCourse.put("total",addCourseList.size());

        //查看待修改课程需要返回两份信息
        HashMap changeCourse = new HashMap<>();
        List<Course> oldChangeCourseList = courseMapper.findByStatus("toChange");
        List<HashMap> changeCourseList = new ArrayList<>();
        for(int i = 0; i<oldChangeCourseList.size();i++){
            HashMap courseMap = new HashMap<>();
            Optional<ChangeCourse> newChangeCourse = changeCourseMapper.findById(oldChangeCourseList.get(i).getCid());
            if(newChangeCourse.isPresent()){
                courseMap.put("old",oldChangeCourseList.get(i));
                courseMap.put("new",newChangeCourse);
            }
            else{
                resMap.put("error","找不到修改信息");
                return resMap;
            }
            changeCourseList.add(courseMap);
        }
        changeCourse.put("res",changeCourseList);
        changeCourse.put("total",changeCourseList.size());

        //将三种状态的课程添加到结果中
        resMap.put("toAdd",addCourse);
        resMap.put("toDelete",deleteCourse);
        resMap.put("toChange",changeCourse);
        Integer addTotal = (Integer) addCourse.get("total");
        Integer changeTotal = (Integer) changeCourse.get("total");
        Integer deleteTotal = (Integer) deleteCourse.get("total");

        resMap.put("total",addTotal+changeTotal+deleteTotal);
        return resMap;
    }



    //录入 lab3版本
    @Override
    public List<Integer> add(String id, String name, String identityid, String mail, String phonenumber, String role,
                             String uschool,
                             String umajor){

        boolean flag = true;
        List<Integer> errorlist=userErrorList(id,identityid,mail,phonenumber);
        for (Integer integer : errorlist) {
            if (integer == 1) {
                flag = false;
                break;
            }
        }


        //5. 专业不为空是否存在
        if(!Objects.equals(umajor,"")){
            if(majorMapper.findMajorByName(umajor)!=null){
                errorlist.add(0);
                //6.专业存在是否与学院对应
                Major major=majorMapper.findMajorByName(umajor);
                if(Objects.equals(major.getSname(), uschool)){
                    errorlist.add(0);
                }
                else{
                    errorlist.add(1);
                    flag=false;
                }
            }
            else {
                errorlist.add(1);
                errorlist.add(1);
                flag = false;
            }
        }
        else{
            errorlist.add(0);
            if(!Objects.equals(uschool, "")){
                if(schoolMapper.findSchoolByName(uschool)!=null)
                    errorlist.add(0);
                else
                    errorlist.add(1);
            }
            else
                errorlist.add(0);

        }

        if(!flag)
            return errorlist;

        User user=new User();

        if(!umajor.equals(""))
            user.setUmajor(umajor);

        if(!uschool.equals(""))
            user.setUschool(uschool);


        user.setID(id);
        user.setIdentityId(identityid);
        user.setMail(mail);
        user.setPhoneNumber(phonenumber);
        user.setRole(role);
        user.setName(name);
        user.setPassword("ABCD1234");
        user.setFirstLogin(0);
        if(Objects.equals(role, "student"))
            user.setUstatus("在读");
        if(Objects.equals(role, "teacher"))
            user.setUstatus("在岗");

        adminMapper.save(user);

        return errorlist;
    }


@Override
public List<Integer> userErrorList(String id, String identityid, String mail, String phonenumber){
    List<Integer> errorlist=new ArrayList<>();
    User user1=adminMapper.findUserById(id);
    if(user1!=null) {
        errorlist.add(1);
        //flag = false;
    }
    else
        errorlist.add(0);

    User user2=adminMapper.findUserByPersonid(identityid);
    if(user2!=null) {
        errorlist.add(1);
        //flag=false;
    }
    else
        errorlist.add(0);

    if(!Objects.equals(mail, "")) {
        List<User> users = adminMapper.findUserByEmail(mail);
        if(users.isEmpty()){
            errorlist.add(0);
        }
        else {
            User user3 = adminMapper.findUserByEmail(mail).get(0);

            errorlist.add(1);
            //flag = false;
        }
    }
    else
        errorlist.add(0);

    if(!Objects.equals(phonenumber, "")) {
        List<User> users = adminMapper.findUserByMobile(phonenumber);
        if(users.isEmpty()){
            errorlist.add(0);
        }
        else {
            User user4 = adminMapper.findUserByMobile(phonenumber).get(0);

            errorlist.add(1);
            //flag = false;
        }
    }
    else
        errorlist.add(0);
    return errorlist;
    }
}




